package com.inossem.allotin.utils;

import android.icu.text.NumberFormat;
import android.os.Build;
import android.text.InputFilter;
import android.text.Spanned;
import android.text.TextUtils;


import com.inossem.allotin.InossemApplication;
import com.inossem.allotin.R;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 数字输入限制工具
 *
 * @author LinH
 */
public class EditInputFilter implements InputFilter {
    /**
     * 最大数字
     */
    private Double maxValue;
    /**
     * 小数点后的数字的位数
     */
    private int pontInt;
    private Pattern pattern;
    /**
     * 是否限制大小
     */
    private boolean isLimitTheSizeOfThe;

    public EditInputFilter(Double maxValue, String unitCode) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            NumberFormat format = NumberFormat.getInstance();
            format.setGroupingUsed(false);
            if (maxValue != null) {
                format.format(maxValue);
            } else {
                format.format(9999999999.9999999999D);
            }

        }
        this.pontInt = (int) Utils.getDecimalPlace(unitCode);
        if (maxValue != null) {
            isLimitTheSizeOfThe = false;
            this.maxValue = maxValue;
        } else {
            isLimitTheSizeOfThe = true;
            this.maxValue = 9999999999.9999999999D;
        }
        // 除数字外的其他的
        pattern = Pattern.compile("[0-9]*");
    }

    /**
     * @param src    新输入的字符串
     * @param start  新输入的字符串起始下标，一般为0
     * @param end    新输入的字符串终点下标，一般为source长度-1
     * @param dest   输入之前文本框内容
     * @param dstart 原内容起始坐标，一般为0
     * @param dend   原内容终点坐标，一般为dest长度-1
     */
    @Override
    public CharSequence filter(CharSequence src, int start, int end, Spanned dest, int dstart, int dend) {
        String oldtext = dest.toString();
        // 验证删除等按键
        if ("".equals(src.toString())) {
            String[] ids = oldtext.split("");
            // 如果删除的是"."
            if (ids[dend].equals(".")) {
                oldtext = oldtext.replace(".", "");
                Double splitDouble = Double.valueOf(oldtext);
                if (splitDouble > this.maxValue) {
                    ToastUtils.showToast(InossemApplication.getContext().getString(R.string.input_module_maximum_number_of_inputs_cannot_be_greater_than) + maxValue);
                    return dest.subSequence(dstart, dend);
                } else {
                    return null;
                }
            } else {
                return null;
            }
        }
        // 验证非数字或者小数点的情况
        Matcher m = pattern.matcher(src);
        if (oldtext.contains(".")) {
            // 已经存在小数点的情况下，只能输入数字
            if (!m.matches()) {
                return null;
            }
        } else {
            // 未输入小数点的情况下，可以输入小数点和数字
            if (!m.matches() && !".".contentEquals(src)) {
                return null;
            }
        }
        // 验证输入金额的大小
        if (!"".equals(src.toString())) {
            if (TextUtils.isEmpty(oldtext)) {
                oldtext = "0";
            }
            double dold = Double.parseDouble(oldtext + src.toString());
            if (dold > maxValue) {
                if (isLimitTheSizeOfThe) {
                    ToastUtils.showToast(InossemApplication.getContext().getString(R.string.input_module_number_entered_cannot_exceed_10_digits));
                    return dest.subSequence(dstart, dend);
                } else {
                    ToastUtils.showToast(InossemApplication.getContext().getString(R.string.input_module_maximum_number_of_inputs_cannot_be_greater_than) + maxValue);
                    return dest.subSequence(dstart, dend);
                }
            } else if (dold == maxValue) {
                if (isLimitTheSizeOfThe) {
                    ToastUtils.showToast(InossemApplication.getContext().getString(R.string.input_module_number_entered_cannot_exceed_10_digits));
                    return dest.subSequence(dstart, dend);
                }
            }
        }
        // 验证小数位精度是否正确
        if (oldtext.contains(".")) {
            int index = oldtext.indexOf(".");
            // 小数位只能2位
            int len = dend - index;
            if (len > pontInt) {
                ToastUtils.showToast(InossemApplication.getContext().getString(R.string.input_module_number_of_digits_after_the_decimal_point_is_zero) + pontInt);
                return dest.subSequence(dstart, dend);
            }
        }
        StringBuilder builder = new StringBuilder(dest);
        builder.insert(dend, src);
        String s = builder.toString();
        String[] split = s.split("\\.");
        if (split.length == 1) {
            Double splitDouble;
            try {
                splitDouble = Double.valueOf(split[0]);
            } catch (Exception e) {
                splitDouble = 0.0;
            }
            if (splitDouble > this.maxValue) {
                ToastUtils.showToast(InossemApplication.getContext().getString(R.string.input_module_maximum_number_of_inputs_cannot_be_greater_than) + maxValue);
                return dest.subSequence(dstart, dend);
            }
        } else if (split.length == 2) {
            double splitInt = Double.valueOf(s);
            if (splitInt > this.maxValue) {
                ToastUtils.showToast(InossemApplication.getContext().getString(R.string.input_module_maximum_number_of_inputs_cannot_be_greater_than_100000000000));
                return dest.subSequence(dstart, dend);
            }
            String splitS = String.valueOf(split[1]);
            if (splitS.length() > this.pontInt) {
                ToastUtils.showToast(InossemApplication.getContext().getString(R.string.input_module_maximum_number_of_inputs_cannot_be_greater_than_100000000000));
                return dest.subSequence(dstart, dend);
            }
        }
        return dest.subSequence(dstart, dend) + src.toString();
    }
}